package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.UserAttr;
import util.Helper;

import dao.UserDao;

public class Regist extends ServletTemplate{
    public void doPost(HttpServletRequest request,
                         HttpServletResponse response) throws IOException, ServletException {
        super.doPost(request, response);
       
        String userPasswd   = this.validatePasswd();
        if(userPasswd.equals("")) {
            this.setRequestAttr("errorInfo", "密码不能为空或两次密码不一致！" + userPasswd);
            this.forward("hint.jsp");
            return;
        }
        
        UserAttr userAttr   = this.genUserAttr(userPasswd);
        String validateInfo = userAttr.validate();
        if(validateInfo != null) {
            this.setRequestAttr("errorInfo", "您的注册信息有误，请确认! " + validateInfo);
            this.forward("hint.jsp");
            return;
        }
        
        UserDao userDao     = new UserDao();
        if(true == userDao.isUser(userAttr.getUserName())) {
            this.setRequestAttr("hintInfo", "!_! 用户名已经存在，请重新换一个！");
            this.forward("hint.jsp");
            return ;
        }
        if(false == userDao.insert(userAttr)) {
            this.setRequestAttr("errorInfo", "!_! 注册失败！");
            this.forward("hint.jsp");
            return;
        }
        userAttr.setUserId(userDao.getLastInsertId());
        this.setLoginInfo(userAttr);
        this.redirect("./polllist");
    }
   
    /**
     * 得到用户属性对象 
     */
    private UserAttr genUserAttr(String userPasswd) {
        UserAttr userAttr   = new UserAttr();
        userAttr.setUserName((String)this.getRequestParam("user_name"));
        userAttr.setUserPasswd(userPasswd);
        userAttr.setUserType(2);
        userAttr.setUserEmail((String)this.getRequestParam("user_email"));
        userAttr.setCreateTime(Helper.getNowTime());
        return userAttr;
    }
   
    /**
     * 验证用户密码不为空且两次密码想同 
     */
    public String validatePasswd() {
        String userPasswd   = (String)this.getRequestParam("user_passwd");
        String reuserPasswd = (String)this.getRequestParam("reuser_passwd");
        if(userPasswd != "" && userPasswd.equals(reuserPasswd)) {
            return userPasswd;
        }
        
        return "";
    }
    
    /**
     * 设置用户的登陆信息 
     */
    private void setLoginInfo(UserAttr userAttr) {
        this.setSessionAttr("userAttr", userAttr);
        //timestamp是毫秒级的
        this.setSessionAttr("validTime", Helper.getTimeStamp() + 3600 * 1000);
    }
}
